<?php
/**
 * Created by PhpStorm.
 * User: JennyWang
 * Date: 2017/4/10
 * Time: 20:49
 */
namespace App\Exceptions;

use Illuminate\Http\Response;

abstract class ApiAbstractException extends \Exception
{
    /**
     * @var int
     */
    protected $code;
    /**
     * @var string
     */
    protected $error;
    const UNKNOWN_MSG = "未定义错误 | undefined error" ;

    /**
     * @var bool
     */
    protected $debug;
    
    public function __construct(
        $code  = ApiErrCode::UNKNOWN_ERROR,
        $error = self::UNKNOWN_MSG,
        $debug = false
    ) {
        $this->code = $code;
        $this->error = $error;
        $this->debug = $debug;

        parent::__construct($error, $code);
    }

    public function response()
    {
        $res_arr = [
            'code' => $this->code,
            'error' => $this->error,
        ];

        if ($this->debug || $this->code === ApiErrCode::UNKNOWN_ERROR) {
            $res_arr['trace'] = $this->getTrace();
        };

        return response($res_arr , Response::HTTP_OK);
    }

    /**
     * For Laravel 5.5+
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function render()
    {
        return $this->response();
    }
}